<template>
    <div>
        <Affix :offset-top="50">
            <Row class="topBtnDiv">
                <Col>
                    <Button type="primary" icon="android-done" @click="AsycDict"> 同步到系统内存</Button>

                </Col>
            </Row>
        </Affix>
        <Row style="margin-top:20px">
            <Col>
                <Spin fix v-show="isLoadingTreeData">正在加载数据...</Spin>
                <div v-show="!isLoadingTreeData" id="SystemModules"></div>
            </Col>
        </Row>

        <Modal v-model="Form.IsShow" :loading="Form.IsLoading" :title="Form.Title" @on-ok="Form.OkEvent"
               @on-cancel="Form.CancelEvent">
            <Form ref="EditForm" :model="Form.Data" label-position="top">
                <Row :gutter="16">
                    <Col :xs="24" :md="12">
                        <FormItem label="名称" prop="sm_name" :rules="{required: true, message:'不能为空', trigger: 'blur'}">
                            <Input v-model="Form.Data.sm_name"></Input>
                        </FormItem>
                    </Col>

                    <Col :xs="24" :md="12">
                        <FormItem label="显示位置" prop="sm_showAddr" >
                            <Select v-model="Form.Data.sm_showAddr+''">
                                <Option value="0">不显示</Option>
                                <Option value="1">头部</Option>
                                <Option value="2">底部</Option>
                                <Option value="3">都显示</Option>
                            </Select>
                        </FormItem>
                    </Col>

                    <Col :xs="24" :md="24">
                        <FormItem label="URL" prop="sm_url" :rules="{required: true, message:'不能为空', trigger: 'blur'}">
                            <Input v-model="Form.Data.sm_url"></Input>
                        </FormItem>
                    </Col>

                    <Col :xs="24" :md="18">
                        <FormItem label="图标" prop="sm_icon">
                            <Input v-model="Form.Data.sm_icon"></Input>
                        </FormItem>
                    </Col>

                    <Col :xs="24" :md="6">
                        <FormItem label="是否打开新页" prop="sm_blank">
                            <i-switch v-model="Form.Data.sm_blank">
                                <span slot="open">是</span>
                                <span slot="close">否</span>
                            </i-switch>
                        </FormItem>
                    </Col>

                    <Col :xs="24" :md="24">
                        <FormItem label="附加属性（JSON 数据）" prop="sm_attr" :rules="{required: false, length:5, message:'字符串过长，限制250个字符', trigger: 'change'}">
                            <Input v-model="Form.Data.sm_attr"></Input>
                        </FormItem>
                    </Col>


                </Row>
            </Form>
        </Modal>


    </div>
</template>

<script>
    import then from "thenjs";
    import AppFrame from "../../../libs/app-frame";
    // var _model = {
    //     'CarType': '车辆类型',
    //     'Goods': '货物类型',
    //     'Exception': '异常情况类型',
    //     'Classes': '班次',
    //     'RoadSection': '路段',
    //     'OrgStructType': '稽查记录审核失败的原因',
    //     'AdoptInfoAuditWrongCause': '稽查记录审核失败的原因'
    // }
    export default {
        data: function () {
            let self = this;
            let MainData = {
                CurSelectNode: null,
                TreeData: []
            };
            let Form = {
                IsShow: false,
                IsLoading: true,
                Data: {},
                OkEvent: function () {
                    self.$refs["EditForm"].validate(valid => {
                        if (valid) {
                            //console.log(Form.Data);
                            AppFrame.Http.Post(
                                "/manage-api/cms/site-menu/EditModule",
                                Form.Data,
                                function (err, ret) {
                                    // console.log(ret);
                                    if (ret && ret.Result === 1) {
                                        let NodeData = self.GetNodeData(ret.Data);
                                        //console.log(NodeData);
                                        if (Form.Data.Type === "Edit") {
                                            self.EditNode(NodeData);
                                        } else {
                                            self.AddNode(NodeData);
                                        }
                                        Form.IsShow = false;
                                        self.$Message.success("操作成功");
                                    } else {
                                        self.$Message.error("操作错误,请重试");
                                        Form.IsLoading = false;
                                        setTimeout(function () {
                                            Form.IsLoading = true;
                                        }, 0);
                                    }
                                }
                            );
                        } else {
                            Form.IsLoading = false;
                            setTimeout(function () {
                                Form.IsLoading = true;
                            }, 0);
                        }
                    });
                },
                CancelEvent: function () {
                }
            };
            return {
                isLoadingTreeData: true,
                MainData: MainData,
                CurSelectNode: null,
                Form: Form,
                FileNameList: []
            };
        },
        created() {
            this.renderTree();
        },
        watch: {
            $route: function () {
                //当路由改变时
                let self = this;
                self.renderTree(true);
            }
        },
        methods: {
            GetTreeData(cb) {
                let self = this;
                var _TreeData = [];

                _TreeData.push({
                    id: "0",
                    text:  "站点栏目",
                    parent: "#",
                    icon: "fa fa-folder"
                });
                //console.log(self.$route.params.label);
                then(function (defer) {
                    self.isLoadingTreeData = true;
                    AppFrame.Http.Post("/manage-api/cms/site-menu/getItems", {}, defer);
                }).then(function (defer, ret) {

                        if (ret && ret.Result === 1) {
                            defer(null, ret.Data);
                        } else {
                            defer({
                                Result: 0
                            });
                        }
                    }).fin(function (defer, err, ret) {
                        if (err) {
                            if (cb) cb(err);
                        } else {
                            // console.log(ret);
                            ret.map(function (item) {
                                let Node = self.GetNodeData(item);
                                _TreeData.push(Node);
                            });

                            self.isLoadingTreeData = false;
                            if (cb) cb(null, _TreeData);
                        }
                    });
            },

            GetNodeData(Module) {

                let Node = {
                    id: Module.sm_id,
                    parent: Module.sm_parentId!==''?Module.sm_parentId:"0",
                    text: Module.sm_name,
                    type: Module.sm_isParent === 1 ? "parent" : "children",
                    a_attr: {
                        //自定义a标签的属性
                        sm_id: Module.sm_id,
                        sm_name: Module.sm_name,
                        sm_parentId: Module.sm_parentId,
                        sm_isParent: Module.sm_isParent,
                        sm_icon: Module.sm_icon,
                        sm_showAddr: Module.sm_showAddr,
                        sm_sort: Module.sm_sort,
                        sm_url: Module.sm_url,
                        sm_blank: Module.sm_blank ? true : false,
                        sm_attr: Module.sm_attr
                    }
                };
                return Node;
            },

            RenderEditForm(type, node) {
                let self = this;
                let TreeData = self.MainData.TreeData;
                self.Form.Title = "添加下级菜单";
                let Model = {
                    Type: type
                };

                if (node) {
                    Model.sm_parentId = node.a_attr.sm_parentId;
                    Model.sm_id = node.a_attr.sm_id;
                    Model.sm_name = node.a_attr.sm_name;
                    Model.sm_showAddr = node.a_attr.sm_showAddr;
                    Model.sm_blank = node.a_attr.sm_blank ? true : false;
                    Model.sm_attr = node.a_attr.sm_attr;
                    Model.sm_icon = node.a_attr.sm_icon;
                    Model.sm_url=node.a_attr.sm_url;
                    Model.ChildrenNode = [];
                    for (let i = 1; i < TreeData.length; i++) {
                        if (TreeData[i].a_attr.ParentID === Model.zd_ID) {
                            Model.ChildrenNode.push(TreeData[i]);
                        }
                    }
                    self.Form.Title = "修改 - " + Model.Name;
                } else {
                    Model.sm_parentId = this.MainData.CurSelectNode.id;
                    Model.ChildrenNode = [];
                    Model.DictID = '';
                    Model.sm_showAddr = 0;
                    Model.sm_icon = "";
                    Model.sm_attr = "";
                    Model.Label = self.$route.params.label; //类型
                    Model.sm_blank = false;
                    Model.sm_url="";
                }
                self.Form.IsShow = true;
                self.Form.Data = Model;
            },

            renderTree(isReflash) {
                let self = this;

                /**初始化JsTree */
                function InitSystemModules() {
                    let tree = null;

                    function initJsTree(TreeData) {

                        $("#SystemModules").on("select_node.jstree", function (e, data) {
                            self.MainData.CurSelectNode = data.node;
                        });

                        $("#SystemModules").on("move_node.jstree", function (e, data) {
                            var TargetNode = tree.get_node(data.parent);
                            var PostData = {
                                CurNodeID: data.node.id,
                                TargetParentID: data.parent,
                                old_parent: data.old_parent,
                                TargetNodeChildrensIDs: TargetNode.children.join(",")
                            };
                            self.CheckIsParent(PostData.TargetParentID);
                            self.CheckIsParent(data.old_parent);
                            AppFrame.Http.Post( "/manage-api/cms/site-menu/MoveNode", PostData, function (err,BackData) {
                                    if (BackData.Result === 0) {
                                        self.$Message.success(BackData.Msg);
                                    }
                                }
                            );
                        });

                        $("#SystemModules").jstree({
                            core: {
                                multiple: false,
                                themes: {
                                    variant: "large",
                                    responsive: false
                                },
                                // so that create works
                                check_callback: true,
                                data: TreeData
                            },
                            types: {
                                default: {
                                    icon: " fa fa-link"
                                },
                                parent: {
                                    icon: " fa fa-bookmark"
                                }
                            },
                            plugins: ["wholerow", "contextmenu", "dnd", "types"],
                            // "state": {
                            //     "key": "SystemModules"
                            // },
                            contextmenu: {
                                items: contextmenu
                            }
                        });

                        tree = $.jstree.reference("#SystemModules");
                    }

                    self.GetTreeData(function (err, TreeData) {
                        self.MainData.TreeData = TreeData;

                        if (isReflash) {
                            let tree = $.jstree.reference("#SystemModules");
                            tree.settings.core.data = TreeData;
                            tree.refresh();
                        } else {
                            initJsTree(TreeData);
                        }
                    });
                }

                function contextmenu(node) {
                    var items = {
                        edititem: {
                            label: "修改",
                            icon: "glyphicon glyphicon-edit ",
                            action: function () {
                                self.RenderEditForm("Edit", node);
                            }
                        },
                        deleteitem: {
                            label: "删除",
                            icon: "glyphicon glyphicon-remove   ",
                            action: function () {
                                self.DeleteNode(node);
                            }
                        },
                        additem: {
                            label: "添加下级",
                            icon: "glyphicon glyphicon-saved ",
                            action: function () {
                                self.RenderEditForm("Add", "");
                            }
                        }
                    };

                    if (node.parent == "#") {
                        delete items.lookitem;
                        delete items.deleteitem;
                        delete items.edititem;
                    }

                    return items;
                }

                InitSystemModules();
            },

            /**
             * 添加 节点
             * @param NodeData
             * @constructor
             */
            AddNode(NodeData) {
                var CurSelectNode = this.MainData.CurSelectNode;
                var tree = $.jstree.reference("#SystemModules");
                tree.create_node(CurSelectNode, NodeData);
                this.CheckIsParent(CurSelectNode.id);
                tree.open_node(CurSelectNode);
                tree.deselect_all();
                tree.select_node(NodeData);
                this.MainData.TreeData.push(NodeData);
            },

            /**
             * 编辑 节点
             * @param NodeData
             * @constructor
             */
            EditNode(NodeData) {
                var CurSelectNode = this.MainData.CurSelectNode;
                CurSelectNode.a_attr = NodeData.a_attr;
                CurSelectNode.text = NodeData.text;
                $.jstree
                    .reference("#SystemModules")
                    .set_text(CurSelectNode, NodeData.text);
            },

            /**
             * 删除节点
             * @param NodeData
             * @constructor
             */
            DeleteNode(node) {
                var self = this;
                this.$Modal.confirm({
                    title: "提示",
                    content: "确实要删除 [" + node.text + "] 吗?",
                    loading: true,
                    onCancel: () => {
                        self.$Modal.remove();
                    },
                    onOk: () => {
                        var AllIchildrenIDs = node.children_d;
                        var AllIDs = AllIchildrenIDs.join(",") + "," + node.id;
                        var PostData = {
                            AllIDs: AllIDs,
                            CurNodeID: node.id,
                            CurNodeParentID: node.a_attr.sm_parentId
                        };

                        var tree = $.jstree.reference("#SystemModules");
                        tree.delete_node(node);
                        self.CheckIsParent(node.a_attr.sm_parentId);
                        var AllIDsArray = AllIDs.split(",");
                        for (var id in AllIDsArray) {
                            if (AllIDsArray[id] != "") {
                                for (var i = self.MainData.TreeData.length - 1; i >= 0; i--) {
                                    if (self.MainData.TreeData[i].id == Number(AllIDsArray[id])) {
                                        self.MainData.TreeData.splice(i, 1);
                                        break;
                                    }
                                }
                            }
                        }

                        AppFrame.Http.Post("/manage-api/cms/site-menu/DelModule", PostData, function (err, BackData) {
                                self.$Modal.remove();
                                if (BackData && BackData.Result === 1) {
                                    self.$Message.success("操作成功");
                                } else {
                                    self.$Message.error("操作失败");
                                }
                            }
                        );
                    }
                });
            },

            AsycDict() {
                let self = this;
                AppFrame.Http.Post("/manage-api/cms/site-menu/AsycDict", {}, function (err, ret) {
                    if (ret && ret.Result === 1) {
                        self.$Message.success("操作成功");
                    } else {
                        self.$Message.error("操作失败");
                    }
                });
            },

            RollBack() {
                var self = this;
                this.RollBackWin.IsShow = true;
                AppFrame.Http.Post("/manage-api/cms/site-menu/GetJsonFile", {}, function (err, ret) {
                    if (ret && ret.Result === 1) {
                        self.FileNameList = ret.Data;
                    }
                });
            },
            DoRollBack() {
                var self = this;
                var selectFileName = self.RollBackWin.FileName;
                if (selectFileName == "") {
                    self.$Message.error("请选择需要恢复的文件");
                    self.RollBackWin.IsLoading = false;
                    setTimeout(function () {
                        self.RollBackWin.IsLoading = true;
                    }, 0);
                }
                AppFrame.Http.Post("/system/cms/site-menu/RollBack", {FileName: selectFileName}, function (err, ret) {
                        if (ret && ret.Result === 1) {
                            self.RollBackWin.IsShow = false;
                            self.$Message.success("恢复成功");
                        }
                    }
                );
            },

            /**
             * 检测是否是父级
             * @param NodeID
             * @constructor
             */
            CheckIsParent(NodeID) {
                if (NodeID == 0) return;
                var tree = $.jstree.reference("#SystemModules");
                var ParentNode = tree.get_node(NodeID);
                if (ParentNode) {
                    if (ParentNode.children.length > 0) {
                        ParentNode.type = "parent";
                        ParentNode.a_attr.sm_isParent = 1;
                        tree.set_icon(ParentNode, "fa fa-bookmark ");
                    } else {
                        ParentNode.type = "children";
                        ParentNode.a_attr.sm_isParent = 0;
                        tree.set_icon(ParentNode, "fa fa-link   ");
                    }
                }
            }
        }
    };
</script>

<style scoped>
    .topBtnDiv {
        line-height: 40px;
        background-color: #fff;
    }
</style>
